import { Op } from 'sequelize'
import { Borrowing } from '../model/borrowing'
export class BorrowingDao {
  queryArrearsList(params: any): Promise<Array<Borrowing>> {
    let where: any = { creator: params.creator }
    if (params.unpaidOnly) where.actualRepaymentDate = null
    return Borrowing.findAll({
      where: where, order: [['date', 'DESC']],
      limit: params.limit,
      offset: params.offset
    })
  }
  count(params: any): Promise<number> {
    let where: any = { creator: params.creator }
    if (params.unpaidOnly) where.actualRepaymentDate = null
    return Borrowing.count({
      where: where
    })
  }
  /**
   * 根据提供的时间范围获取数据
   * @param {*} params
   * @param {Date} params.startDate
   * @param {Date} params.endDate
   * @param {Date} params.creator
   */
  queryArrearsListByDateRange(params: any): Promise<Array<Borrowing>> {
    const endDate = new Date(params.endDate)
    return Borrowing.findAll({
      where: {
        date: {
          [Op.lt]: endDate
        },
        creator: params.creator,
        [Op.or]: [
          { actualRepaymentDate: null },
          { actualRepaymentDate: { [Op.lt]: endDate } }
        ]
      }
    })
  }
  upsertArrears(params: any): Promise<any> {
    return Borrowing.upsert(params)
  }
  deleteArrears(params: any): Promise<number> {
    return Borrowing.destroy({ where: params })
  }
}
